<?php

namespace App\Http\Controllers\TK_Api;

use App\Http\Requests\Common\CommentStoreRequest;
use App\Models\Comment;
use App\Models\User;
use DB;
use Illuminate\Http\JsonResponse;

class CommentController extends ApiBaseController
{

    /**
     * 创建
     * @return JsonResponse|object
     */
    public function store(CommentStoreRequest $request) {
        $params = $request->validated();
        $params['userId'] = $this->user->id;
        $params['parentId'] = (empty($params['parentId']) OR $params['parentId'] == 0) ? null: $params['parentId'];

        if (!empty($params['atUserId'])) {
            $atUser = User::find($params['atUserId']);
            if ($atUser) {
                $params['content'] = '@' . $atUser->nickname . ' ' . $params['content'];
            }
        }

        if (!empty($params['parentId'])) {
            $parentComment = Comment::find($params['parentId']);
            // 非顶级
            if ($parentComment && $parentComment->parentId != null) {
                $params['parentId'] = $parentComment->parentId;
                if(empty($params['atUserId'])) {
                    $toUser = User::find($parentComment->userId);
                    if($toUser) {
                        $params['content'] = '@' . $toUser->nickname . ' ' . $params['content'];
                    }
                }
            }
        }

        $comment = new Comment($params);
        $result = $comment->save();

        $data = null;
        if($result) {
            $data = Comment::where('comments.id', $comment->id)
                ->join('user', 'comments.userId', '=', 'user.id')
                ->leftJoin('user_like_comment', function ($join) {
                    $join->on('comments.id', '=', 'user_like_comment.commentId')
                        ->where('user.id', '=', isset($this->user) ? $this->user->id : 0);
                })
                ->selectRaw('comments.id, comments.content, comments.created_at, comments.like, user.id as userId, user.avatar, user.nickname, user.username, IF(user_like_comment.id IS NULL, false, true) as liked')
                ->first();
        }

        return $this->restful($data);
    }

    /**
     * 删除
     * @param $id
     * @return JsonResponse|object
     */
    public function delete($id) {
       $result = Comment::where('id', $id)->where('userId', $this->user->id)->delete();

        return $this->restful($result);
    }

    /**
     * 获取题目下的所有评论
     * @param $id
     * @return JsonResponse|object
     */
    public function getCommentByQuestionId($id) {
        $list = Comment::where('questionId', $id)
            ->whereNull('parentId')
            ->join('user', 'comments.userId', '=', 'user.id')
            ->leftJoin('user_like_comment', function ($join) {
                $join->on('comments.id', '=', 'user_like_comment.commentId')
                    ->where('user_like_comment.userId', isset($this->user) ? $this->user->id : 0);
            })
            ->with(['children' => function($q) {
                $q->join('user', 'comments.userId', '=', 'user.id')
                    ->leftJoin('user_like_comment', function ($join) {
                        $join->on('comments.id', '=', 'user_like_comment.commentId')
                            ->where('user_like_comment.userId', isset($this->user) ? $this->user->id : 0);
                    })->selectRaw('parentId, comments.id, comments.content, comments.created_at, comments.like, user.id as userId, user.avatar, user.nickname, user.username, IF(user_like_comment.id IS NULL, false, true) as liked')
                    ->orderByDesc('comments.created_at');
            }])
            ->selectRaw('comments.id, comments.content, comments.created_at, comments.like, user.id as userId, user.avatar, user.nickname, user.username, IF(user_like_comment.id IS NULL, false, true) as liked')
            ->orderByDesc('comments.created_at')
            ->get();

        return $this->restful($list);
    }

    /**
     * 喜欢/取消喜欢
     * @param $id
     * @return JsonResponse|object
     */
    public function like($id) {
        $comment = Comment::find($id);
        if ($comment) {
            DB::transaction(function () use ($id, $comment) {
                $this->user->likeComment()->toggle($id);
                $count = DB::table('user_like_comment')->where('commentId', $id)->count();
                $comment->like = $count;
                $comment->save();
            });
        }

        return $this->restful();
    }
}
